<template>
  <d2-container>
    <el-card shadow="never" class="d2-mb">
      <el-form
        class="filter-container"
        ref="BZForm"
        :model="BZForm"
        label-width="85px"
      >
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="币种名称">
               <el-input v-model="BZForm.name" style="width:100%;"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="4" style="">
          <el-button type="primary" size="small" @click="handle_currencyChange" style='margin-top:3px;'>
            <d2-icon name="search" /> 查询
          </el-button>
        </el-col>
        </el-row>
      </el-form>
    </el-card>
    <div class="mb">
      <el-button type="default" size="mini" @click="add_currency">
        <d2-icon name="plus" />
        新增
      </el-button>
      <el-button type="default" size="mini" @click="edit_currency">
        <d2-icon name="edit" />
        修改
      </el-button>
      <el-button type="default" size="mini" icon="el-icon-delete" @click="del_currency">
        删除
      </el-button>
      <!-- <el-button type="default" size="mini" @click="examine">
        <d2-icon name="search" />
        查看
      </el-button> -->
      <el-upload
            class="upload-btn"
            :action="uploadUrl"
            accept=".xls, .xlsx"
            :on-success="handleAvatarSuccess"
            :on-progress="uploadProgress"
            :on-error="handleUploadError"
            :show-file-list="false" style="display:inline-block;margin:0 10px;">
          <el-button type="default" size="small">
            <d2-icon name="download" />
            导入
          </el-button>
          </el-upload>
      <!-- <el-button type="default" size="mini" @click="handleFormSubmit">
        <d2-icon name="upload" />
        导出
      </el-button> -->
      <el-button type="default" size="mini" @click="qy_currency">
        <d2-icon name="unlock" />
        启用
      </el-button>
      <el-button type="default" size="mini" @click="qy_currency">
        <d2-icon name="unlock-alt" />
        停用
      </el-button>
      <el-button
        type="default"
        size="mini"
        @click="handle_refreshCurrent"
      >
        <d2-icon name="refresh" />
        刷新
      </el-button>
    </div>
    <el-card shadow="never" class="d2-mb">
      <el-table :data="currencytableData" :header-cell-style="{ background: '#eef1f6' }" border highlight-current-row @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40"> </el-table-column>
        <el-table-column type="index" :index="indexMethod" label="序号" sortable width="75"></el-table-column>
        <el-table-column prop="status" label="状态" sortable :formatter="formatterStatus"></el-table-column>
        <el-table-column prop="id" label="币种ID" sortable v-if="a"></el-table-column>
        <el-table-column prop="name" label="币种名称" sortable></el-table-column>
        <el-table-column prop="symbol" label="币种符号" sortable></el-table-column>
        <el-table-column prop="is_base" label="是否本位币" sortable :formatter="formatterbase"></el-table-column>
      </el-table>
    </el-card>
    <!-- 新增 -->
    <el-dialog :visible.sync="currencyVisible" title="币种信息-新增">
      <div>
    <div class="mb">
      <el-button type="default" size="mini" @click="addRow">
        <d2-icon name="plus" />
        增行
      </el-button>
      <el-button type="default" size="mini" icon="el-icon-delete" @click="delData">
        删行
      </el-button>
    </div>
    <el-form label-position="right" status-icon :rules="rules" :model="add_currencytableData" ref="ruleForm">
    <el-table :data="add_currencytableData" border :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow'>
        <el-table-column type="selection" width="45" align="center"></el-table-column>
      <el-table-column type="index" :index="indexMethod" label="序号" width="55">
      </el-table-column>
      <el-table-column label="状态" sortable width="100">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.status'" :rules="rules.status">
          <el-select  clearable v-model="scope.row.status" placeholder="请选择" filterable allow-create>
			         <el-option label="停用" value="0"></el-option>
               <el-option label="启用" value="1"></el-option>
			     </el-select>
            </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="code" label="币种ID*" sortable>
        <template slot-scope="scope">
         <el-select  clearable v-model="scope.row.code" clearable class="filter-item" placeholder="请选择">
             <el-option label="USD(美元)" value="USD"></el-option>
              <el-option label="CNY(人民币)" value="CNY"></el-option>
              <el-option label="EUR(欧元)" value="EUR"></el-option>
              <el-option label="GBP(英镑)" value="GBP"></el-option>
          </el-select>
        </template>
      </el-table-column> -->
      <el-table-column label="币种名称" width="150">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.name'" :rules="rules.name">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.name"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="币种符号" width="100">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.symbol'" :rules="rules.symbol">
          <!-- <el-input
             placeholder="请输入币种符号，如：¥"
            v-model="scope.row.symbol"
          ></el-input> -->
          <el-select v-model="scope.row.symbol" filterable allow-create default-first-option placeholder="请选择币种符号">
            <el-option v-for="item in options" :key="item.symbol" :label="item.label" :value="item.symbol">
            </el-option>
          </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="是否本位币" width="110">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.is_base'" :rules="rules.is_base">
          <el-select  clearable v-model="scope.row.is_base" placeholder="请选择" filterable allow-create>
			         <el-option label="非本位币" value="0"></el-option>
               <el-option label="本位币" value="1"></el-option>
			     </el-select>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
    </el-form>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="currencyVisible = false">取消</el-button>
        <el-button type="primary" @click="currencyChange('ruleForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog :visible.sync="edit_currencyVisible" title="币种信息-修改">
      <div>
            <el-form label-position="right" status-icon :rules="rules" :model="edit_currencytableData" ref="ruleForm">
    <el-table :data="edit_currencytableData" border>
      <el-table-column type="index" :index="indexMethod" label="序号" width="55">
      </el-table-column>
      <el-table-column label="状态" width="100" sortable>
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.status'" :rules="rules.status">
          <el-select  clearable v-model="scope.row.status" placeholder="请选择" filterable allow-create>
			         <el-option label="停用" value="0"></el-option>
               <el-option label="启用" value="1"></el-option>
			     </el-select>
            </el-form-item>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="币种ID" width="100">
        <template slot-scope="scope">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.id"
            disabled
          ></el-input>
        </template>
      </el-table-column>
     <el-table-column label="币种名称" width="150">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.name'" :rules="rules.name">
          <el-input
            placeholder="请输入内容"
            v-model="scope.row.name"
          ></el-input>
           </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="币种符号" width="100">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.symbol'" :rules="rules.symbol">
           <el-select v-model="scope.row.symbol" filterable allow-create default-first-option placeholder="请选择币种符号">
            <el-option v-for="item in options" :key="item.symbol" :label="item.label" :value="item.symbol">
            </el-option>
          </el-select>
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="是否本位币" width="110">
        <template slot-scope="scope">
          <el-form-item :prop="scope.$index + '.is_base'" :rules="rules.is_base">
          <el-select  clearable v-model="scope.row.is_base" placeholder="请选择" filterable allow-create>
			         <el-option label="非本位币" value="0"></el-option>
               <el-option label="本位币" value="1"></el-option>
			     </el-select>
          </el-form-item>
        </template>
      </el-table-column>
    </el-table>
            </el-form>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="edit_currencyVisible = false">取消</el-button>
        <el-button type="primary" @click="edit_currencyChange('ruleForm')"
          >保存</el-button
        >
      </span>
    </el-dialog>
     <!-- 导入 -->
    <el-dialog :visible.sync="drcurrencyVisible" title="导入币种信息">
      <div>
    <el-table :data="drcurrencytableData" border :cell-style="{ 'text-align': 'center' }" :header-cell-style="{ 'text-align': 'center' }" @selection-change='selectRow'>
      <el-table-column type="index" label="序号">
      </el-table-column>
      <el-table-column prop="status" label="状态">
      </el-table-column>
      <el-table-column prop="name" label="币种名称" sortable>
      </el-table-column>
      <el-table-column prop="symbol" label="币种符号" sortable>
      </el-table-column>
      <el-table-column prop="is_base" label="是否本位币" sortable>
      </el-table-column>
    </el-table>
  </div>
      <span span slot="footer" class="dialog-footer">
        <el-button @click="drcurrencyVisible = false">取消</el-button>
        <el-button type="primary" @click="drcurrency"
          >上传数据</el-button
        >
      </span>
    </el-dialog>
  </d2-container>
</template>

<script>
import DemoPageFooter from "../../../components/PageFooter";
import { conCurrency, addCurrency } from '../../../api/url_lcc';
export default {
  //币种信息
  name: "currency_information",
  components: {
    "demo-page-footer": DemoPageFooter,
  },
  data() {
    return {
      options: [{
          symbol: 'CNY',
          label: 'CNY（人民币）'
        }, {
          symbol: 'USD',
          label: 'USD（美元）'
        }, {
          symbol: 'EUR',
          label: 'EUR（欧元）'
        }],
        symbol: [],
      a:false,
       // 导入
      uploadUrl:`/user/lead/`,
      drcurrencyVisible:false,
      drcurrencytableData:[],
      row: "",
      rowNum: 1,
      currencyVisible: false,
      edit_currencyVisible: false,
      currencytableData:[],
      add_currencytableData:[],
      edit_currencytableData:[],
      BZForm: {
        code:"",
        name:"",
      },
      page: {
        pageCurrent: 1,
        pageSize: 10,
        pageTotal: 0
      },
      ruleForm:{
        status:"",
        name:"",
        symbol:"",
        is_base:"",
      },
      rules:{
         status: [
           { required: true, message: '请选择状态', trigger: 'change' }
          ],
          name: [
           { required: true, message: '请输入币种名称', trigger: 'blur' },
         ],
          symbol: [
           { required: true, message: '请输入币种符号', trigger: 'blur' },
         ],
         is_base: [
           { required: true, message: '请选择是否本位币', trigger: 'change' }
         ],
           
      }
    };
  },
   created() {
           this.tabledatas.map(i => {
               i.show = false
               return i
           })
  },
  methods: {
     // 导入
      handleAvatarSuccess (res, file) {
        // this.uploadloading.close();
        console.log(444444,res.result);
        if (res && res.errcode === "1") {
           this.$message({
           message: '导入成功',
           type: 'success',
          })
          this.drcurrencyVisible = true;
          this.drcurrencytableData = [];
          var data1 = res.result.Sheet1;
          for (var i = 0; i < data1.length; i++) {
            this.drcurrencytableData[i] = {
               status: data1[i].状态,
               name: data1[i].币种名称,
               symbol: data1[i].币种符号,
               is_base: data1[i].是否本位币,
            }
          }
         
        } else {
          this.$message.error(res.msg);
        }
      },
      drcurrency(){
         var drcurrencytableData = [];
        var drcurrencytableData = this.drcurrencytableData;
        drcurrencytableData.forEach(function(item, index) {
           var data1 = item.status
           var data2 = item.is_base
          if (data1 == "停用") {
             item.status = '0';
         } else if (data1 == "启用") {
             item.status = '1';
         }
          if (data2 == "非本位币") {
             item.is_base = '0';
         } else if (data2 == "本位币") {
             item.is_base = '1';
         }
       })
        let params = { 
          "operation":"ADD",
          curr:this.drcurrencytableData
        };
        addCurrency(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                this.drcurrencyVisible = false;
                this.handle_currencyChange();
            }).catch(err =>{
          this.$message.error(err.msg);
        });
      },
    // 可用状态
     formatterStatus(row,column){
        return row.status == 0?'停用':'启用'
    },
    // 币种符号
     formattersym(row, column) {
         if (row.symbol == "¥") {
             return '¥(人民币)';
         } else if (row.symbol == "$") {
             return '$(美元)';
         } else if (row.symbol == "€") {
             return '€(欧元)';
         } else if (row.symbol == "￡") {
             return '￡(英镑)';
         }
     },
    // 是否是本位币
     formatterbase(row,column){
        return row.is_base == "0"?'非本位币':'本位币'
    },
    // 行内编辑
    handleCellDataChange({ rowIndex, key, value, row }) {
      console.log(rowIndex);
      console.log(key);
      console.log(value);
      console.log(row);
    },
    // 多选
    handleSelectionChange(val) {
       this.multipleSelection = val;
       console.log('删除1',this.multipleSelection)
     },
      // 获取表格选中时的数据
      selectRow (val) {
        this.selectlistRow = val
      },
      // 增加行
      addRow () {
       	  var list = {
          rowNum:this.rowNum,
        //   "code":"",    
          "status": "",	
          "name": "",
          "symbol":"",
          "is_base":""
   		 };
        this.add_currencytableData.unshift(list)
        this.rowNum += 1;
      },
      // 删除方法
      // 删除选中行
      delData () {
        console.log(121,this.selectlistRow.length)
        if(this.selectlistRow.length == 0){
          this.$message.error('请勾选要删除的行！');
        }else{
          for (let i = 0; i < this.selectlistRow.length; i++) {
          let val = this.selectlistRow
          val.forEach((val, index) => {
            this.add_currencytableData.forEach((v, i) => {
              if (val.rowNum === v.rowNum) {
                // i 为选中的索引
                this.add_currencytableData.splice(i, 1)
              }
            })
          })
        }
        // 删除完数据之后清除勾选框
        this.$refs.table.clearSelection()
        }
        
      },
      // 多选提示
    openMessage() {
      this.$message({
          dangerouslyUseHTMLString: true,
          type: 'error',
          message: '<strong>请勾选你要选择的行，再进行操作！</strong>'
      });
    },
     // 查询
    handle_currencyChange(){
       let params = {
            "name": this.BZForm.name || "",
        };
        conCurrency(params).then(res => {
            // if (res.errcode == "1") {
                this.currencytableData = []
                var data = res.result
                for (var i = 0; i < data.length; i++) {
                this.currencytableData[i] = {
                   currency: data[i]['currency'],
                   id: data[i]['id'],
                   is_base: data[i]['is_base'].toString(),
                   name: data[i]['name'],
                   status: data[i]['status'].toString(),
                   symbol: data[i]['symbol'],
                }
               }
             }).catch(err =>{
          this.$message.error(err.msg);
        });
    },
    // 新增
    add_currency(){
        this.currencyVisible = true;
    },
    // 新增保存
    currencyChange(ruleForm){
      let params = {
           "operation":"ADD",
            "curr":this.add_currencytableData
        };
       const rule1 = new Promise((resolve, reject) => {
        this.$refs[ruleForm].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
       Promise.all([rule1]).then(() => {
        addCurrency(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.currencyVisible = false
                 this.handle_currencyChange()
           }).catch(err =>{
          this.$message.error(err.msg);
        });
         });
    },
    // 修改
    edit_currency(){
      var data = this.multipleSelection
      if (this.multipleSelection == undefined) {
          this.openMessage();
      } else if(this.multipleSelection.length != 1){
         this.$message.error("修改只能选中一条数据进行！");
      } 
      // else if(this.multipleSelection[0].id == '1' || this.multipleSelection[0].id == '2' || this.multipleSelection[0].id == '3'){
      //   this.$message.error("默认数据不支持修改！");
      // }
      else{
         this.edit_currencyVisible = true
         this.edit_currencytableData = this.multipleSelection
      }
    },
    // 修改保存
    edit_currencyChange(ruleForm){
      let params = {
           "operation":"MOD",
            "curr":{
              "id":this.edit_currencytableData[0].id,
              "status": this.edit_currencytableData[0].status,
              "name": this.edit_currencytableData[0].name,
              "symbol":this.edit_currencytableData[0].symbol,
              "is_base":this.edit_currencytableData[0].is_base
            }
        };
         const rule1 = new Promise((resolve, reject) => {
        this.$refs[ruleForm].validate(valid => {
          if (valid) {
            resolve();
          } else {
            console.log("error submit!!");
            return false;
          }
        });
      });
       Promise.all([rule1]).then(() => {
        addCurrency(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.edit_currencyVisible = false
                 this.handle_currencyChange()
            }).catch(err =>{
          this.$message.error(err.msg);
        });
         });
    },
    // 删除
    del_currency(){
       this.$confirm('是否删除该币种信息?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
           this.del_list()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
     
    },
    // 删除列表数组
    del_list(){
           var data = this.multipleSelection
           var currList  = [];
           data.forEach(function(item, index) {
              var data1 = item.id
              currList.push(data1)
              console.log(90,data1,91,currList)
          })
          // if(currList.indexOf(1) == '0'||currList.indexOf(2) == '0'||currList.indexOf(3) == '0'){
          //   this.$message.error("默认数据不支持删除！");
          // }else{
               let params = {
           "operation":"DEL",
           "curr": currList
        };
        addCurrency(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.handle_currencyChange()
            }).catch(err =>{
          this.$message.error(err.msg);
        });
          // }
         
    },
    // 启用/ 停用
    qy_currency(){
      var data = this.multipleSelection
           var currList  = [];
           data.forEach(function(item, index) {
              var data1 = item.id
              currList.push(data1)
              console.log(90,data1,91,currList)
          })
      //       if(currList.indexOf(1) == '0'||currList.indexOf(2) == '0'||currList.indexOf(3) == '0'){
      //       this.$message.error("默认数据不支持修改状态！");
      // }else{
      let params = {
           "operation":"STATUS",
            "curr": currList
        };
        addCurrency(params).then(res => {
            // if (res.errcode == "1") {
                this.$message.success(res.result);
                 this.handle_currencyChange()
            }).catch(err =>{
          this.$message.error(err.msg);
        });
          // }
    },
    // 刷新
    handle_refreshCurrent(){
      this.BZForm.name = "",
      this.handle_currencyChange()
    }
  },
   mounted() {
    this.handle_currencyChange()

}
};
</script>
<style></style>
